import { signOut } from 'next-auth/react';
import { useDisconnect } from 'wagmi';
import { 
  Button, 
  Text, 
  HStack, 
  Avatar, 
  useToast,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalBody,
  ModalCloseButton,
  Input,
  VStack,
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  useDisclosure,
  Drawer,
  DrawerBody,
  DrawerHeader,
  DrawerOverlay,
  DrawerContent,
  DrawerCloseButton,
  List,
  ListItem,
  ListIcon,
  Divider,
  Box
} from '@chakra-ui/react';
import { getEllipsisTxt } from 'utils/format';
import { useState, useEffect } from 'react';
import { createHash } from 'crypto';
import { CheckCircleIcon, LockIcon, StarIcon, InfoIcon } from '@chakra-ui/icons';

const STORAGE_KEY = 'user_login_hash';

const ConnectButton = () => {
  const { disconnectAsync } = useDisconnect();
  const toast = useToast();
  const { isOpen: isModalOpen, onOpen: onModalOpen, onClose: onModalClose } = useDisclosure();
  const { isOpen: isDrawerOpen, onOpen: onDrawerOpen, onClose: onDrawerClose } = useDisclosure();
  const [inputValue, setInputValue] = useState('');
  const [hashValue, setHashValue] = useState('');
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  // 组件加载时从 localStorage 读取登录状态
  useEffect(() => {
    const storedHash = localStorage.getItem(STORAGE_KEY);
    if (storedHash) {
      setHashValue(storedHash);
    }
  }, []);

  const handleInputConfirm = () => {
    if (inputValue) {
      // 生成哈希值
      const hash = `0x${createHash('sha256').update(inputValue).digest('hex')}`;
      // 保存到 state 和 localStorage
      setHashValue(hash);
      localStorage.setItem(STORAGE_KEY, hash);
      onModalClose();
      
      toast({
        title: '登录成功',
        description: '您的登录状态已保存',
        status: 'success',
        position: 'top-right',
        isClosable: true,
      });
    }
  };

  const handleAuth = () => {
    onModalOpen();
  };

  const handleDisconnect = async () => {
    await disconnectAsync();
    signOut({ callbackUrl: '/' });
    // 清除 state 和 localStorage
    setHashValue('');
    setInputValue('');
    localStorage.removeItem(STORAGE_KEY);
    
    toast({
      title: '已退出登录',
      description: '您的登录状态已清除',
      status: 'info',
      position: 'top-right',
      isClosable: true,
    });
  };

  const handlePersonalCenter = () => {
    setIsMenuOpen(false);
    onDrawerOpen();
  };

  if (hashValue) {
    return (
      <>
        <Menu isOpen={isMenuOpen} onClose={() => setIsMenuOpen(false)}>
          <MenuButton onClick={() => setIsMenuOpen(!isMenuOpen)}>
            <HStack cursor={'pointer'}>
              <Avatar size="xs" />
              <Text fontWeight="medium">{getEllipsisTxt(hashValue)}</Text>
            </HStack>
          </MenuButton>
          <MenuList>
            <MenuItem onClick={handlePersonalCenter}>个人中心</MenuItem>
            <MenuItem onClick={handleDisconnect}>退出登录</MenuItem>
          </MenuList>
        </Menu>

        <Drawer
          isOpen={isDrawerOpen}
          placement="right"
          onClose={onDrawerClose}
          size="md"
        >
          <DrawerOverlay />
          <DrawerContent>
            <DrawerCloseButton />
            <DrawerHeader borderBottomWidth="1px">个人中心</DrawerHeader>
            <DrawerBody>
              <VStack spacing={6} align="stretch">
                <Box>
                  <HStack spacing={4} mb={4}>
                    <Avatar size="xl" />
                    <VStack align="start" spacing={1}>
                      <Text fontSize="xl" fontWeight="bold">
                        {getEllipsisTxt(hashValue)}
                      </Text>
                      <Text fontSize="sm" color="gray.500">
                        用户ID: {getEllipsisTxt(hashValue)}
                      </Text>
                    </VStack>
                  </HStack>
                </Box>

                <Divider />

                <List spacing={4}>
                  <ListItem>
                    <HStack>
                      <ListIcon as={CheckCircleIcon} color="green.500" />
                      <Text fontWeight="medium">可验证凭证</Text>
                      <Text color="gray.500">12 个</Text>
                    </HStack>
                  </ListItem>
                  <ListItem>
                    <HStack>
                      <ListIcon as={LockIcon} color="blue.500" />
                      <Text fontWeight="medium">助记词</Text>
                      <Text color="gray.500">（修改）</Text>
                    </HStack>
                  </ListItem>
                  <ListItem>
                    <HStack>
                      <ListIcon as={StarIcon} color="yellow.500" />
                      <Text fontWeight="medium">已验证资源</Text>
                      <Text color="gray.500">8 个</Text>
                    </HStack>
                  </ListItem>
                  <ListItem>
                    <HStack>
                      <ListIcon as={InfoIcon} color="purple.500" />
                      <Text fontWeight="medium">账户状态</Text>
                      <Text color="green.500">正常</Text>
                    </HStack>
                  </ListItem>
                </List>

                <Divider />

                <Button colorScheme="red" onClick={handleDisconnect}>
                  退出登录
                </Button>
              </VStack>
            </DrawerBody>
          </DrawerContent>
        </Drawer>
      </>
    );
  }

  return (
    <>
      <Button size="sm" onClick={handleAuth} colorScheme="blue">
        登录
      </Button>

      <Modal isOpen={isModalOpen} onClose={onModalClose}>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>请输入助记词</ModalHeader>
          <ModalCloseButton />
          <ModalBody pb={6}>
            <VStack spacing={4}>
              <Input 
                placeholder="请输入助记词"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
              />
              <Button colorScheme="blue" onClick={handleInputConfirm} width="100%">
                确认
              </Button>
            </VStack>
          </ModalBody>
        </ModalContent>
      </Modal>
    </>
  );
};

export default ConnectButton;
